﻿using Dapper;

using HBase;
using HBase.db;
using hCommand;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Persistence.abs {
    public abstract class AbsCoreStockServer : AbsExtendsServer, ICoreStockServer {
        public CoreStock getCoreStockByLocId(int locId) {
            String sql = "select * from [Core_stock] where  status>-1 and loc_Id=@locId";
            CoreStock cs = readConn().QueryUnique<CoreStock>(sql ,new { locId = locId });
            return cs;
        }

        public List<CoreStock> getCoreStockByStatus(StockStatus status) {
            string sql = "select a.* from Core_stock a  where   1=1   and status=@status";
            
            return readConn().Query<CoreStock>(sql, new { status =(int)status }).ToList();
        }
        public Page<CoreStock> QueryCoreStockPage(CoreStockDto dto) {
            string sql = "select a.* from Core_stock a  where   1=1  "; 
            if( dto.stockStatus != 0 ) {
                sql += " and status=@stockStatus";
            } else {
                sql += " and status >0  and status<70 ";
            }

            if( !string.IsNullOrEmpty(dto.name) ) {
                dto.name = "%" + dto.name + "%";
                sql += " AND name like @name ";
            }
            if( dto.rareaId != 0 ) {

                sql += " AND d_Item_id = @rareaId ";
            }
            if( dto.locId != 0 ) {
                sql += $" AND loc_Id like '%{dto.locId}%' ";
            }
            if (!string.IsNullOrEmpty(dto.boxCode))
            {
                sql += $" AND box_Code like '%{dto.boxCode}%' ";
            }
            if (dto.pkId > 0) {
                sql += " AND pk_id = @pkId ";
            } else if (dto.pkId < 0) {
                dto.pkId = -dto.pkId;
                sql += " AND pk_id <> @pkId ";
            } 
            if (dto.classTypes > 0) {
                sql += " AND classify_Id = @classTypes ";

            } 
            if (dto.shelfId > 0) {
                dto.shelfId *= 100000;
                sql += " AND loc_id>@shelfId AND loc_id<@shelfId+100000";

            } 
            return this.queryPage<CoreStock>(sql ,"box_code" ,dto);
        } 
        public  CoreStock getCoreStockByCode(string code) {
            string sql = @"SELECT *  FROM Core_stock  WHERE   box_Code = @boxCode and status >=0 and status <70";

            return readConn().QueryUnique<CoreStock>(sql, new { boxCode = code });
           
        } 
     
        public long UpdateStatusByStockId(long stockId ,StockStatus status) {
            string sql = @"UPDATE  core_stock SET status =@status WHERE id=@stockId";
            return opConn().Execute(sql ,new { stockId = stockId ,status = ( int ) status });
        } 
    }
}
